import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import time
from fastapi.middleware.cors import CORSMiddleware
from config.config import TORTOISE_ORM
# from utils.elasticsearch_client import es_client  # 暂时注释，等 ES 启动后再打开
import logging
from utils.auth_middleware import AuthMiddleware
from views.myviews.custser import custser_router
from views.users import users_router
from views.myviews.individual import indiv_router
from utils.timed import add_jobs, scheduler
from tortoise.contrib.fastapi import register_tortoise
from views.rag.chat import chat_router
import traceback

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


app = FastAPI()


# ========== 全局异常处理器 ==========
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """捕获所有未处理的异常，打印详细堆栈"""
    error_traceback = ''.join(
        traceback.format_exception(type(exc), exc, exc.__traceback__)
    )
    logger.error("❌ 全局异常捕获:\n%s", error_traceback)
    return JSONResponse(
        status_code=500,
        content={"detail": f"服务器内部错误: {str(exc)}"}
    )


# ========== 中间件配置（重要：按照添加顺序倒序执行） ==========

# 1. 调试中间件 m1（最外层，最先执行）
@app.middleware("http")
async def m1(request: Request, call_next):
    print("m1 request")
    start = time.time()
    response = await call_next(request)
    print("m1 response")
    end = time.time()
    response.headers["ProcessTimer"] = str(end - start)
    return response


# 2. 调试中间件 m2
@app.middleware("http")
async def m2(request: Request, call_next):
    print("m2 request")
    response = await call_next(request)
    response.headers["author"] = "moluo"
    print("m2 response")
    return response


# 定义允许跨域请求的来源列表
origins = [
    "http://localhost",
    "http://localhost:5173",
    "http://127.0.0.1:5173",
    "http://localhost:8080",
    "http://127.0.0.1:8080",
    "http://localhost:3000",
    "http://127.0.0.1:3000",
]

# 3. 添加认证中间件（先添加，后执行）
app.add_middleware(AuthMiddleware)

# 4. 添加 CORS 中间件（后添加，先执行 - 确保 CORS 头优先处理）
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# ========== 路由配置 ==========

# 注册路由
app.include_router(users_router)
app.include_router(indiv_router)

app.include_router(custser_router)

# 导入并注册通知路由
from views.notifications import notifications_router
app.include_router(notifications_router)

app.include_router(chat_router)

# ========== 定时任务配置 ==========
@app.on_event("startup")
def startup_event():
    """应用启动时，启动调度器并添加任务"""
    import asyncio
    from utils.timed import set_main_loop

    # 获取当前事件循环并传递给定时任务模块
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.get_event_loop()

    set_main_loop(loop)
    add_jobs()
    scheduler.start()
    print("✅ 调度器已启动，事件循环已注册")


@app.on_event("shutdown")
def shutdown_event():
    """应用关闭时，关闭调度器"""
    scheduler.shutdown()
    print("✅ 调度器已关闭")


@app.get("/")
def read_root():
    return {"Hello": "World"}


# ========== Tortoise ORM 初始化 ==========
register_tortoise(
    app,
    config=TORTOISE_ORM,
    generate_schemas=True,  # 自动创建表（开发环境）
    add_exception_handlers=True,
)


if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
